package com.jic.market.impl.rest.discount;

import com.alibaba.fastjson.JSON;
import com.jic.common.base.vo.RestResult;
import com.jic.market.entity.PromotionGiftItemEntity;
import com.jic.market.entity.PromotionRuleEntity;
import com.jic.market.mapper.DiscountConditionGiftDetailMapper;
import com.jic.market.mapper.PromotionGiftItemEntityMapper;
import com.jic.market.mapper.coupon.CouponDetailMapper;
import com.jic.market.request.rest.coupon.CouponReceiveOfPersonRequest;
import com.jic.market.response.rest.discount.GiftDetail;
import com.jic.market.service.rest.coupon.CouponRestService;
import com.jic.market.service.rest.discount.GiftService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author yinhaijun
 * @date: 2020/5/12
 */
@Slf4j
@Service
public class GiftServiceImpl implements GiftService {
    @Autowired
    private DiscountConditionGiftDetailMapper discountConditionGiftDetailMapper;
    @Autowired
    private PromotionGiftItemEntityMapper promotionGiftItemEntityMapper;
    @Autowired
    private CouponRestService couponRestService;
    @Autowired
    private CouponDetailMapper couponDetailMapper;
    @Override
    public List<GiftDetail> getGiftDetails(String promotionId, String promotionCode, String thirdUserId, PromotionRuleEntity promotionRuleEntity, Long overlayAppNum) {
        PromotionGiftItemEntity promotionGiftItemEntityQ = new PromotionGiftItemEntity();
        promotionGiftItemEntityQ.setPromotionId(Long.parseLong(promotionId));
        promotionGiftItemEntityQ.setPromotionRuleId(promotionRuleEntity.getId());
        List<PromotionGiftItemEntity> promotionGiftItemEntityList = promotionGiftItemEntityMapper.findAll(promotionGiftItemEntityQ);
        List<GiftDetail> giftDetailList = new ArrayList<>();
        if(null != promotionGiftItemEntityList && !promotionGiftItemEntityList.isEmpty()){
            Long finalOverlayAppNum = overlayAppNum.longValue();
            promotionGiftItemEntityList.forEach(promotionGiftItemEntity -> {
                GiftDetail giftDetail = new GiftDetail();
                giftDetail.setGiftType(promotionGiftItemEntity.getGiftType());
                giftDetail.setCouponPromotionId(promotionGiftItemEntity.getCouponId());
                giftDetail.setThirdProductCode(promotionGiftItemEntity.getMpCode());
                giftDetail.setUpgradeAmount(promotionGiftItemEntity.getUpgradeAmount());
                if(null == promotionGiftItemEntity.getGiftNum()){
                    giftDetail.setNum(1L * finalOverlayAppNum);
                }else {
                    giftDetail.setNum(promotionGiftItemEntity.getGiftNum() * finalOverlayAppNum);
                }
                // 渠道限制
                Long channelStoreLimit = promotionGiftItemEntityQ.getChannelStoreLimit();
                // 个人限制
                Long channelIndividualLimit = promotionGiftItemEntityQ.getChannelIndividualLimit();
                if(giftDetail.getGiftType().equals(1)){
                    // 获取可用的商品数量
                    Long userCountNum = discountConditionGiftDetailMapper.countGoodsNumByUser(promotionCode, giftDetail.getThirdProductCode(), thirdUserId);
                    Long countNum = discountConditionGiftDetailMapper.countGoodsNum(promotionCode, giftDetail.getThirdProductCode());
                    Long num = getUsedNum(giftDetail.getNum(), channelStoreLimit, channelIndividualLimit, userCountNum, countNum);
                    giftDetail.setNum(num);
                }else {
                    // 获取可用的优惠券或红包数量
                    Long userCountNum = discountConditionGiftDetailMapper.countCouponNumByUser(promotionCode, giftDetail.getThirdProductCode(), thirdUserId);
                    Long countNum = discountConditionGiftDetailMapper.countCouponNum(promotionCode, giftDetail.getThirdProductCode());
                    Long num = getUsedNum(giftDetail.getNum(), channelStoreLimit, channelIndividualLimit, userCountNum, countNum);
                    giftDetail.setNum(num);
                }
                giftDetailList.add(giftDetail);
            });
        }
        return giftDetailList;
    }

    @Override
    public List<GiftDetail> getMixedGiftDetails(List<GiftDetail> requestGiftDetailList, List<GiftDetail> giftDetailList) {
        List<GiftDetail> giftDetailList1 = new ArrayList<>();
        // 取交集
        if(null != requestGiftDetailList && !requestGiftDetailList.isEmpty()){
            for(int i = requestGiftDetailList.size() - 1; i>=0; i--){
                GiftDetail requestGiftDetail = requestGiftDetailList.get(i);
                for(GiftDetail giftDetail: giftDetailList){
                    if(requestGiftDetail.getGiftType().equals(1)){//商品
                        if(requestGiftDetail.getThirdProductCode().equals(giftDetail.getThirdProductCode())){
                            // 数量取最小
                            if(giftDetail.getNum() < requestGiftDetail.getNum()){
                                requestGiftDetail.setNum(giftDetail.getNum());
                            }
                            giftDetailList1.add(requestGiftDetail);
                        }
                    }
                    else if(requestGiftDetail.getGiftType().equals(4) || requestGiftDetail.getGiftType().equals(5)){
                        if(requestGiftDetail.getCouponPromotionId().equals(giftDetail.getCouponPromotionId())){
                            // 数量取最小
                            if(giftDetail.getNum() < requestGiftDetail.getNum()){
                                requestGiftDetail.setNum(giftDetail.getNum());
                            }
                            giftDetailList1.add(requestGiftDetail);
                        }
                    }
                }
            }
        }
        return giftDetailList1;
    }

    @Override
    public void issuanceGift(List<GiftDetail> giftDetailList, String thirdUserId) {
        if (null != giftDetailList && !giftDetailList.isEmpty()) {
            for (GiftDetail giftDetail : giftDetailList) {
                if (giftDetail.getGiftType().equals(4)
                        || giftDetail.getGiftType().equals(5)) {
                    // 发放优惠券
                    for(Long i = giftDetail.getNum(); i>=1L; i--){
                        CouponReceiveOfPersonRequest couponReceiveOfPersonRequest = new CouponReceiveOfPersonRequest();
                        couponReceiveOfPersonRequest.setPromotionId(giftDetail.getCouponPromotionId());
                        couponReceiveOfPersonRequest.setThirdUserId(thirdUserId);
                        RestResult<Boolean> restResult = couponRestService.receiveCoupon(couponReceiveOfPersonRequest);
                        log.info("赠送活动：用户" + thirdUserId + "发券" + JSON.toJSONString(restResult));
                        //TODO 返回优惠券Code存储
                    }
                }
            }
        }
    }

    @Override
    public void recycleGift(List<GiftDetail> giftDetailList, String thirdUserId) {
        if (null != giftDetailList && !giftDetailList.isEmpty()) {
            for (GiftDetail giftDetail : giftDetailList) {
                if (giftDetail.getGiftType().equals(4)
                        || giftDetail.getGiftType().equals(5)) {
                    // 回收优惠券
                    long flag = couponDetailMapper.updateStatus(giftDetail.getCouponCodeList(), 4);//优惠券作废
                }
            }
        }
    }

    @Override
    public Long getUsedNum(Long num, Long channelStoreLimit, Long channelIndividualLimit, Long userCountNum, Long countNum) {
        // 取最小
        if(null != countNum && null != channelStoreLimit){
            if(countNum + num > channelStoreLimit){
                num = channelStoreLimit - countNum <= 0 ? 0 : channelStoreLimit - countNum;
            }
        }
        if(null != userCountNum && null != channelIndividualLimit){
            if(userCountNum + num > channelIndividualLimit){
                num = channelIndividualLimit - userCountNum <= 0 ? 0 : channelIndividualLimit - userCountNum;
            }
        }
        return num;
    }
}
